from flask import render_template, request, redirect, url_for, flash, session
from extensions import db
from models import User, Student, Teacher, Course, LearningPath, Exercise, StudentExercise, Recommendation
from functools import wraps
from datetime import datetime

# 登录装饰器
def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'user_id' not in session:
            flash('请先登录', 'danger')
            return redirect(url_for('login'))
        return f(*args, **kwargs)
    return decorated_function

# 角色检查装饰器
def role_required(role):
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            if 'role' not in session or session['role'] != role:
                flash(f'只有{role}才能访问此页面', 'danger')
                return redirect(url_for('dashboard'))
            return f(*args, **kwargs)
        return decorated_function
    return decorator

def register_routes(app):
    # 首页
    @app.route('/')
    def index():
        return render_template('index.html')
    
    # 注册
    @app.route('/register', methods=['GET', 'POST'])
    def register():
        if request.method == 'POST':
            username = request.form.get('username')
            email = request.form.get('email')
            password = request.form.get('password')
            role = request.form.get('role')
            
            # 检查用户是否已存在
            existing_user = User.query.filter_by(username=username).first()
            if existing_user:
                flash('用户名已存在', 'danger')
                return redirect(url_for('register'))
                
            existing_email = User.query.filter_by(email=email).first()
            if existing_email:
                flash('邮箱已被注册', 'danger')
                return redirect(url_for('register'))
            
            # 创建新用户
            user = User(username=username, email=email, role=role)
            user.set_password(password)
            db.session.add(user)
            db.session.commit()
            
            # 根据角色创建相应记录
            if role == 'student':
                student = Student(user_id=user.id, grade='', interests='')
                db.session.add(student)
            else:
                teacher = Teacher(user_id=user.id, subject='', bio='')
                db.session.add(teacher)
            db.session.commit()
            
            flash('注册成功，请登录', 'success')
            return redirect(url_for('login'))
            
        return render_template('register.html')
    
    # 登录
    @app.route('/login', methods=['GET', 'POST'])
    def login():
        if request.method == 'POST':
            username = request.form.get('username')
            password = request.form.get('password')
            
            user = User.query.filter_by(username=username).first()
            
            if not user or not user.check_password(password):
                flash('用户名或密码错误', 'danger')
                return redirect(url_for('login'))
            
            session['user_id'] = user.id
            session['username'] = user.username
            session['role'] = user.role
            
            flash(f'欢迎回来, {user.username}!', 'success')
            return redirect(url_for('dashboard'))
            
        return render_template('login.html')
    
    # 登出
    @app.route('/logout')
    def logout():
        session.clear()
        flash('您已成功登出', 'info')
        return redirect(url_for('index'))
    
    # 控制面板（根据角色重定向）
    @app.route('/dashboard')
    @login_required
    def dashboard():
        if session['role'] == 'student':
            return redirect(url_for('student_dashboard'))
        else:
            return redirect(url_for('teacher_dashboard'))
    
    # 学生控制面板
    @app.route('/student/dashboard')
    @login_required
    @role_required('student')
    def student_dashboard():
        user_id = session['user_id']
        student = Student.query.filter_by(user_id=user_id).first()
        
        # 获取学生的练习成绩数据
        exercises_data = StudentExercise.query.filter_by(student_id=student.id).all()
        
        # 获取个性化学习路径
        learning_paths = LearningPath.query.filter_by(student_id=student.id).all()
        
        # 获取教师推荐
        recommendations = Recommendation.query.filter_by(student_id=student.id).all()
        
        return render_template('student/dashboard.html', 
                              student=student, 
                              exercises_data=exercises_data,
                              learning_paths=learning_paths,
                              recommendations=recommendations)
    
    # 学生个性化学习路径
    @app.route('/student/learning_paths')
    @login_required
    @role_required('student')
    def student_learning_paths():
        user_id = session['user_id']
        student = Student.query.filter_by(user_id=user_id).first()
        learning_paths = LearningPath.query.filter_by(student_id=student.id).all()
        return render_template('student/learning_paths.html', learning_paths=learning_paths)
    
    # 学生智能问答
    @app.route('/student/ai_qa', methods=['GET', 'POST'])
    @login_required
    @role_required('student')
    def student_ai_qa():
        if request.method == 'POST':
            question = request.form.get('question')
            # 这里应该实现智能问答的逻辑，返回答案
            answer = "这是智能问答系统的回答示例。在实际应用中，这里会调用智能问答API。"
            return render_template('student/ai_qa.html', question=question, answer=answer)
        return render_template('student/ai_qa.html')
    
    # 学生练习
    @app.route('/student/exercises')
    @login_required
    @role_required('student')
    def student_exercises():
        user_id = session['user_id']
        student = Student.query.filter_by(user_id=user_id).first()
        
        # 获取所有可用练习
        exercises = Exercise.query.all()
        
        # 获取学生已完成的练习
        completed_exercises = StudentExercise.query.filter_by(student_id=student.id).all()
        completed_ids = [ce.exercise_id for ce in completed_exercises]
        
        return render_template('student/exercises.html', 
                              exercises=exercises, 
                              completed_ids=completed_ids)
    
    # 学生做练习
    @app.route('/student/exercise/<int:exercise_id>', methods=['GET', 'POST'])
    @login_required
    @role_required('student')
    def student_do_exercise(exercise_id):
        user_id = session['user_id']
        student = Student.query.filter_by(user_id=user_id).first()
        exercise = Exercise.query.get_or_404(exercise_id)
        
        if request.method == 'POST':
            answers = request.form.get('answers')
            
            # 简单评分逻辑（实际应用中应该有更复杂的评分系统）
            score = 85.0  # 示例分数
            
            # 保存学生练习记录
            student_exercise = StudentExercise(
                student_id=student.id,
                exercise_id=exercise.id,
                score=score,
                answers=answers,
                completion_time=datetime.utcnow()
            )
            db.session.add(student_exercise)
            db.session.commit()
            
            flash(f'练习完成，得分: {score}', 'success')
            return redirect(url_for('student_exercises'))
            
        return render_template('student/do_exercise.html', exercise=exercise)
    
    # 学生数据概览
    @app.route('/student/analytics')
    @login_required
    @role_required('student')
    def student_analytics():
        user_id = session['user_id']
        student = Student.query.filter_by(user_id=user_id).first()
        
        # 获取学生的练习数据
        exercises_data = StudentExercise.query.filter_by(student_id=student.id).all()
        
        # 计算分析数据
        total_exercises = len(exercises_data)
        avg_score = sum([ex.score for ex in exercises_data]) / total_exercises if total_exercises > 0 else 0
        
        # 获取练习的难度分布
        difficulty_distribution = {}
        for ex in exercises_data:
            exercise = Exercise.query.get(ex.exercise_id)
            difficulty = exercise.difficulty
            if difficulty in difficulty_distribution:
                difficulty_distribution[difficulty] += 1
            else:
                difficulty_distribution[difficulty] = 1
        
        return render_template('student/analytics.html', 
                              total_exercises=total_exercises,
                              avg_score=avg_score,
                              difficulty_distribution=difficulty_distribution,
                              exercises_data=exercises_data)
    
    # 教师控制面板
    @app.route('/teacher/dashboard')
    @login_required
    @role_required('teacher')
    def teacher_dashboard():
        user_id = session['user_id']
        teacher = Teacher.query.filter_by(user_id=user_id).first()
        
        # 获取教师的课程
        courses = Course.query.filter_by(teacher_id=teacher.id).all()
        
        return render_template('teacher/dashboard.html', 
                              teacher=teacher,
                              courses=courses)
    
    # 教师管理学生
    @app.route('/teacher/students')
    @login_required
    @role_required('teacher')
    def teacher_manage_students():
        # 获取所有学生
        students = Student.query.all()
        return render_template('teacher/students.html', students=students)
    
    # 教师查看学生详情
    @app.route('/teacher/student/<int:student_id>')
    @login_required
    @role_required('teacher')
    def teacher_view_student(student_id):
        student = Student.query.get_or_404(student_id)
        user = User.query.get(student.user_id)
        
        # 获取学生的练习数据
        exercises_data = StudentExercise.query.filter_by(student_id=student.id).all()
        
        return render_template('teacher/student_detail.html', 
                              student=student,
                              user=user,
                              exercises_data=exercises_data)
    
    # 教师推荐学习内容
    @app.route('/teacher/recommend/<int:student_id>', methods=['GET', 'POST'])
    @login_required
    @role_required('teacher')
    def teacher_recommend(student_id):
        user_id = session['user_id']
        teacher = Teacher.query.filter_by(user_id=user_id).first()
        student = Student.query.get_or_404(student_id)
        
        if request.method == 'POST':
            content = request.form.get('content')
            
            recommendation = Recommendation(
                teacher_id=teacher.id,
                student_id=student.id,
                content=content
            )
            db.session.add(recommendation)
            db.session.commit()
            
            flash('推荐已发送给学生', 'success')
            return redirect(url_for('teacher_view_student', student_id=student.id))
            
        return render_template('teacher/recommend.html', student=student)
    
    # 教师管理课程
    @app.route('/teacher/courses')
    @login_required
    @role_required('teacher')
    def teacher_courses():
        user_id = session['user_id']
        teacher = Teacher.query.filter_by(user_id=user_id).first()
        courses = Course.query.filter_by(teacher_id=teacher.id).all()
        return render_template('teacher/courses.html', courses=courses)
    
    # 教师添加/编辑课程
    @app.route('/teacher/course/<int:course_id>', methods=['GET', 'POST'])
    @app.route('/teacher/course/new', methods=['GET', 'POST'])
    @login_required
    @role_required('teacher')
    def teacher_edit_course(course_id=None):
        user_id = session['user_id']
        teacher = Teacher.query.filter_by(user_id=user_id).first()
        
        if course_id:
            course = Course.query.get_or_404(course_id)
            # 确保只有课程创建者可以编辑
            if course.teacher_id != teacher.id:
                flash('您没有权限编辑此课程', 'danger')
                return redirect(url_for('teacher_courses'))
        else:
            course = Course(teacher_id=teacher.id)
            
        if request.method == 'POST':
            course.title = request.form.get('title')
            course.description = request.form.get('description')
            
            if not course_id:  # 新课程
                db.session.add(course)
                
            db.session.commit()
            flash('课程已保存', 'success')
            return redirect(url_for('teacher_courses'))
            
        return render_template('teacher/edit_course.html', course=course)
    
    # 教师管理练习
    @app.route('/teacher/course/<int:course_id>/exercises')
    @login_required
    @role_required('teacher')
    def teacher_course_exercises(course_id):
        course = Course.query.get_or_404(course_id)
        exercises = Exercise.query.filter_by(course_id=course_id).all()
        return render_template('teacher/course_exercises.html', 
                              course=course,
                              exercises=exercises)
    
    # 教师添加/编辑练习
    @app.route('/teacher/course/<int:course_id>/exercise/<int:exercise_id>', methods=['GET', 'POST'])
    @app.route('/teacher/course/<int:course_id>/exercise/new', methods=['GET', 'POST'])
    @login_required
    @role_required('teacher')
    def teacher_edit_exercise(course_id, exercise_id=None):
        course = Course.query.get_or_404(course_id)
        
        if exercise_id:
            exercise = Exercise.query.get_or_404(exercise_id)
        else:
            exercise = Exercise(course_id=course_id)
            
        if request.method == 'POST':
            exercise.title = request.form.get('title')
            exercise.content = request.form.get('content')
            exercise.difficulty = int(request.form.get('difficulty'))
            
            if not exercise_id:  # 新练习
                db.session.add(exercise)
                
            db.session.commit()
            flash('练习已保存', 'success')
            return redirect(url_for('teacher_course_exercises', course_id=course_id))
            
        return render_template('teacher/edit_exercise.html', 
                              course=course,
                              exercise=exercise) 